import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

import { Food } from '../entities';

import { CreateFoodReqDto, FoodListReqDto } from './dto/food.dto';

@Injectable()
export class FoodService {
  constructor(
    @InjectRepository(Food)
    private readonly foodsRepository: Repository<Food>,
  ) {}

  async create(food: CreateFoodReqDto) {
    const findFood = await this.foodsRepository.findOne({
      where: { name: food.name, isDeleted: false },
    });
    if (findFood) {
      throw new HttpException('食物已存在', HttpStatus.BAD_REQUEST);
    }

    const newFood = this.foodsRepository.create({
      name: food.name,
      imageUrl: food.imageUrl,
      category: food.category,
      rating: food.rating,
      microElement: food.microElement,
    });
    return await this.foodsRepository.save(newFood);
  }

  findAll(params: FoodListReqDto) {
    return this.foodsRepository.find({
      where: { isDeleted: false, ...params },
    });
  }

  findOne(foodId: number) {
    return this.foodsRepository.findOne({
      where: { foodId, isDeleted: false },
    });
  }

  // update(foodId: string, updateFoodDto: UpdateFoodDto) {
  //   return this.prisma.food.update({
  //     where: { foodId },
  //     data: updateFoodDto as any,
  //   });
  // }

  async fakeRemove(foodId: number) {
    const findFood = await this.foodsRepository.findOne({
      where: { foodId, isDeleted: false },
    });
    if (!findFood) {
      throw new HttpException('食物不存在', HttpStatus.BAD_REQUEST);
    }
    findFood.isDeleted = true;
    return this.foodsRepository.save(findFood);
  }
}
